<template>
  <div 
    :class="['component-wrapper', { 'component-selected': isSelected }]"
    :style="componentStyle"
    :data-component-id="component.id"
    @click.stop="onSelect"
    @mousedown="onMouseDown"
  >
    <!-- 根据组件类型渲染不同的组件 -->
    <component 
      :is="resolveComponent(component.type)"
      v-bind="resolvedProps"
    />
    
    <!-- 选中时显示的操作按钮 -->
    <div v-if="isSelected" class="component-actions">
      <div class="action-btn delete-btn" @click.stop="onDelete" title="删除组件">
        <span>🗑️</span>
      </div>
      <div class="action-btn copy-btn" @click.stop="onCopy" title="复制组件">
        <span>📋</span>
      </div>
    </div>
    
    <!-- 选中时显示的拖拽手柄 -->
    <div v-if="isSelected" class="resize-handles">
      <div class="resize-handle top-left" @mousedown.stop="onResizeStart('top-left')"></div>
      <div class="resize-handle top-right" @mousedown.stop="onResizeStart('top-right')"></div>
      <div class="resize-handle bottom-left" @mousedown.stop="onResizeStart('bottom-left')"></div>
      <div class="resize-handle bottom-right" @mousedown.stop="onResizeStart('bottom-right')"></div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, ref } from 'vue'
import { usePageStore, type ComponentItem } from '@/stores/page'
import { useDataPoolStore } from '@/stores/dataPool'
import { v4 as uuidv4 } from 'uuid'

const dataPoolStore = useDataPoolStore()

// 组件属性
const props = defineProps<{
  component: ComponentItem
  isSelected: boolean
}>()

// 组件事件
const emit = defineEmits<{
  select: [id: string]
  move: [id: string, deltaX: number, deltaY: number]
}>()

const pageStore = usePageStore()

// 处理组件属性的数据绑定
const resolvedProps = computed(() => {
  const result = { ...props.component.props }
  
  // 应用属性的数据绑定
  if (props.component.dataBindings && props.component.dataBindings.length > 0) {
    props.component.dataBindings.forEach(binding => {
      const { propName, dataId } = binding
      
      // 处理普通属性绑定（非样式属性）
      if (!propName.startsWith('style:')) {
        const dataValue = dataPoolStore.getDataItemValue(dataId)
        if (dataValue !== undefined) {
          result[propName] = dataValue
        }
      }
    })
  }
  
  return result
})

// 组件样式
const componentStyle = computed(() => {
  // 确保所有样式属性都被正确应用
  const style = { ...props.component.style }
  
  // 确保位置样式属性存在
  if (!style.position) style.position = 'absolute'
  if (!style.top) style.top = '0px'
  if (!style.left) style.left = '0px'
  
  // 确保尺寸样式属性存在
  if (!style.width) style.width = 'auto'
  if (!style.height) style.height = 'auto'
  
  // 确保z-index存在
  if (!style.zIndex) style.zIndex = 1
  
  // 应用样式属性的数据绑定
  if (props.component.dataBindings && props.component.dataBindings.length > 0) {
    props.component.dataBindings.forEach(binding => {
      const { propName, dataId } = binding
      
      // 处理样式属性绑定
      if (propName.startsWith('style:')) {
        const styleKey = propName.substring(6) // 去掉 'style:' 前缀
        const dataValue = dataPoolStore.getDataItemValue(dataId)
        if (dataValue !== undefined) {
          style[styleKey] = dataValue
        }
      }
    })
  }
  
  return style
})

// 选择组件
const onSelect = () => {
  emit('select', props.component.id)
}

// 删除组件
const onDelete = () => {
  if (confirm('确定要删除此组件吗？')) {
    pageStore.removeComponent(props.component.id)
  }
}

// 复制组件
const onCopy = () => {
  const newComponent = JSON.parse(JSON.stringify(props.component))
  newComponent.id = uuidv4() // 生成新的ID
  
  // 调整位置，避免完全重叠
  const top = parseFloat(newComponent.style.top as string) || 0
  const left = parseFloat(newComponent.style.left as string) || 0
  
  newComponent.style.top = `${top + 20}px`
  newComponent.style.left = `${left + 20}px`
  
  // 添加到页面
  pageStore.addComponent(newComponent)
}

// 拖拽相关状态
const isDragging = ref(false)
const startX = ref(0)
const startY = ref(0)

// 鼠标按下事件
const onMouseDown = (event: MouseEvent) => {
  // 如果点击的是调整大小的手柄，不触发拖拽
  if ((event.target as HTMLElement).classList.contains('resize-handle')) {
    return
  }
  
  // 选中组件
  onSelect()
  
  // 开始拖拽
  isDragging.value = true
  startX.value = event.clientX
  startY.value = event.clientY
  
  // 添加鼠标移动和松开事件监听
  document.addEventListener('mousemove', onMouseMove)
  document.addEventListener('mouseup', onMouseUp)
  
  // 阻止默认行为和冒泡
  event.preventDefault()
  event.stopPropagation()
}

// 鼠标移动事件
const onMouseMove = (event: MouseEvent) => {
  if (!isDragging.value) return
  
  // 计算移动距离
  const deltaX = event.clientX - startX.value
  const deltaY = event.clientY - startY.value
  
  // 更新起始位置
  startX.value = event.clientX
  startY.value = event.clientY
  
  // 触发移动事件
  emit('move', props.component.id, deltaX, deltaY)
}

// 鼠标松开事件
const onMouseUp = () => {
  isDragging.value = false
  
  // 移除事件监听
  document.removeEventListener('mousemove', onMouseMove)
  document.removeEventListener('mouseup', onMouseUp)
}

// 调整大小相关状态
const isResizing = ref(false)
const resizeHandle = ref('')

// 开始调整大小
const onResizeStart = (handle: string) => {
  isResizing.value = true
  resizeHandle.value = handle
  
  // 记录起始位置
  startX.value = event?.clientX || 0
  startY.value = event?.clientY || 0
  
  // 添加鼠标移动和松开事件监听
  document.addEventListener('mousemove', onResizeMove)
  document.addEventListener('mouseup', onResizeEnd)
  
  // 阻止默认行为和冒泡
  event?.preventDefault()
  event?.stopPropagation()
}

// 调整大小时的鼠标移动
const onResizeMove = (event: MouseEvent) => {
  if (!isResizing.value) return
  
  // 获取组件当前样式
  const style = props.component.style
  const currentWidth = parseFloat(style.width as string) || 100
  const currentHeight = parseFloat(style.height as string) || 100
  const currentTop = parseFloat(style.top as string) || 0
  const currentLeft = parseFloat(style.left as string) || 0
  
  // 计算移动距离
  const deltaX = event.clientX - startX.value
  const deltaY = event.clientY - startY.value
  
  // 更新起始位置
  startX.value = event.clientX
  startY.value = event.clientY
  
  // 根据不同的调整手柄更新样式
  const updates: any = {}
  
  switch (resizeHandle.value) {
    case 'top-left':
      updates.width = `${currentWidth - deltaX}px`
      updates.height = `${currentHeight - deltaY}px`
      updates.left = `${currentLeft + deltaX}px`
      updates.top = `${currentTop + deltaY}px`
      break
    case 'top-right':
      updates.width = `${currentWidth + deltaX}px`
      updates.height = `${currentHeight - deltaY}px`
      updates.top = `${currentTop + deltaY}px`
      break
    case 'bottom-left':
      updates.width = `${currentWidth - deltaX}px`
      updates.height = `${currentHeight + deltaY}px`
      updates.left = `${currentLeft + deltaX}px`
      break
    case 'bottom-right':
      updates.width = `${currentWidth + deltaX}px`
      updates.height = `${currentHeight + deltaY}px`
      break
  }
  
  // 更新组件样式
  pageStore.updateComponent(props.component.id, { style: updates })
}

// 结束调整大小
const onResizeEnd = () => {
  isResizing.value = false
  
  // 移除事件监听
  document.removeEventListener('mousemove', onResizeMove)
  document.removeEventListener('mouseup', onResizeEnd)
}

// 根据组件类型解析对应的组件
const resolveComponent = (type: string) => {
  // 这里可以根据组件类型返回对应的组件
  // 实际项目中可能需要动态导入或注册组件
  switch (type) {
    case 'input':
      return 'input'
    case 'select':
      return 'select'
    case 'button':
      return 'button'
    case 'text':
      return 'div'
    case 'container':
      return 'div'
    // 其他组件类型...
    default:
      return 'div'
  }
}
</script>

<style lang="scss" scoped>
.component-wrapper {
  position: absolute;
  box-sizing: border-box;
  min-width: 50px;
  min-height: 30px;
  
  &.component-selected {
    outline: 2px solid #409eff;
    outline-offset: 1px;
  }
  
  .component-actions {
    position: absolute;
    top: -30px;
    right: 0;
    display: flex;
    gap: 4px;
    
    .action-btn {
      width: 24px;
      height: 24px;
      display: flex;
      align-items: center;
      justify-content: center;
      background-color: #fff;
      border: 1px solid #ddd;
      border-radius: 4px;
      cursor: pointer;
      font-size: 12px;
      
      &:hover {
        background-color: #f5f5f5;
      }
      
      &.delete-btn:hover {
        background-color: #fef0f0;
        color: #f56c6c;
      }
    }
  }
  
  .resize-handles {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
    pointer-events: none;
    
    .resize-handle {
      position: absolute;
      width: 8px;
      height: 8px;
      background-color: #fff;
      border: 1px solid #409eff;
      pointer-events: auto;
      
      &.top-left {
        top: -4px;
        left: -4px;
        cursor: nwse-resize;
      }
      
      &.top-right {
        top: -4px;
        right: -4px;
        cursor: nesw-resize;
      }
      
      &.bottom-left {
        bottom: -4px;
        left: -4px;
        cursor: nesw-resize;
      }
      
      &.bottom-right {
        bottom: -4px;
        right: -4px;
        cursor: nwse-resize;
      }
    }
  }
}
</style>